package com.ym.jiujiangeyou.service;

import java.io.File;

import com.ym.jiujiangeyou.R;
import com.ym.jiujiangeyou.util.DownloadUtils;
import com.ym.jiujiangeyou.util.FileManager;

import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;

/**
 * @author 叶铭
 * @email yeming_1001@163.com
 * @version V1.0
 * @Description: 后台下载更新app
 */
public class AppUpgradeService extends Service {

	public static final int APP_VERSION_LATEST = 0;
	public static final int APP_VERSION_OLDER = 1;
	public static final int DOWNLOAD_ALEARD = 1;
	private static final int DOWNLOAD_FAIL = -1;
	private static final int DOWNLOAD_SUCCESS = 0;
	
	public static final int notificationId = 100;
	private String downloadUrl = null;
	private String downloadFileName = null;
	private NotificationManager notificationManager = null;
	private Notification notification = null;
	private PendingIntent pendingIntent = null;
	
	private File fileDir = null;
	private File file = null;
	
	AlertDialog.Builder builder ;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case DOWNLOAD_SUCCESS:
				Toast.makeText(getApplicationContext(), "success",
						Toast.LENGTH_LONG).show();
				// install();
				break;
			case DOWNLOAD_FAIL:
				Toast.makeText(getApplicationContext(), "fail",
						Toast.LENGTH_LONG).show();
				notification.contentView.setViewVisibility(
						R.id.app_upgrade_progressblock, View.GONE);
				notification.defaults = Notification.DEFAULT_SOUND;
				notification.contentIntent = pendingIntent;
				notification.contentView.setTextViewText(
						R.id.app_upgrade_progresstext, "下载失败。");
				notificationManager.notify(notificationId, notification);
				// notificationManager.cancel(notificationId);
				break;
			case DOWNLOAD_ALEARD:
				Toast.makeText(getApplicationContext(), "已有安装包",
						Toast.LENGTH_LONG).show();
				builder = new AlertDialog.Builder(getApplication()) ;
				builder.setTitle("提示").setMessage("立即安装?");
				builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						//notificationManager = MoreFragment.this.getActivity().getSystemService(NOTIFICATION_SERVICE);
					install(file) ;
					}
				});
				break;
			default:
				break;
			}
		}
	};

	public AppUpgradeService() {
	}

	private DownloadUtils.DownloadListener downloadListener = new DownloadUtils.DownloadListener() {

		@Override
		public void downloading(int progress) {
			// TODO Auto-generated method stub
			notification.contentView.setProgressBar(
					R.id.app_upgrade_progressbar, 100, progress, false);
			notification.contentView.setTextViewText(
					R.id.app_upgrade_progresstext, progress + "%");
			notificationManager.notify(notificationId, notification);
		}

		@Override
		public void downloaded() {
			// TODO Auto-generated method stub
			notification.contentView.setViewVisibility(
					R.id.app_upgrade_progressblock, View.GONE);
			notification.defaults = Notification.DEFAULT_SOUND;
			notification.contentIntent = pendingIntent;
			notification.contentView.setTextViewText(
					R.id.app_upgrade_progresstext, "下载完成,点击安装.");
			notificationManager.notify(notificationId, notification);
			if (file.exists() && file.isFile()) {
				Message msg = handler.obtainMessage();
				msg.what = DOWNLOAD_SUCCESS;
				handler.sendMessage(msg);
			}
			// notificationManager.cancel(notificationId);
		}

	};

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;

	}

	@Override
	@Deprecated
	public void onStart(Intent intent, int startId) {
		// TODO Auto-generated method stub
		downloadUrl = intent.getStringExtra("downloadUrl");
		downloadFileName = intent.getStringExtra("fileName");
		/*System.out.println("----------1-----------" + downloadUrl + "/////---"
				+ downloadFileName);

		fileDir = new File(FileManager.getSaveApkPath());
		System.out.println("-------------fileDir--------" + fileDir + "-----"
				+ fileDir.exists());
		if (fileDir.exists()) {
			File file = new File(fileDir.getPath() + "/"
					+ downloadFileName);
			System.out.println("-------------file--------"
					+ file.getPath());
			if (file.exists() && file.isFile()) {
				Message msg = handler.obtainMessage();
				msg.what = DOWNLOAD_ALEARD;
				handler.sendMessage(msg);
				stopSelf();
				return;
			}
		}*/ /*
		 * else { return super.onStartCommand(intent, flags, startId); }
		 */
		System.out.println("-------------1-1-------");
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notification = new Notification();
		notification.contentView = new RemoteViews(getApplication()
				.getPackageName(), R.layout.appupgrade_notification);
		//System.out.println("-------------1-2-------");
		
		/*Intent completingIntent = new Intent();
		completingIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		completingIntent.setClass(getApplication().getApplicationContext(),
				AppUpgradeService.class);*/
		Intent completingIntent = getInstallIntent(new File(FileManager.getSaveApkPath() + "/"
					+ downloadFileName)) ;
		
		//System.out.println("-------------1-3-------");
		pendingIntent = PendingIntent.getActivity(AppUpgradeService.this,
				R.string.app_name, completingIntent,
				PendingIntent.FLAG_UPDATE_CURRENT);
		notification.icon = R.drawable.icon_collect_press;
		notification.tickerText = "开始下载";
		notification.contentIntent = pendingIntent;
		notification.contentView.setProgressBar(R.id.app_upgrade_progressbar,
				100, 0, false);
		notification.contentView.setTextViewText(
				R.id.app_upgrade_progresstext, "0%");
		notificationManager.cancel(notificationId);
		notificationManager.notify(notificationId, notification);
		// new AppUpgradeThread().start();
	//	System.out.println("-------------1-4-------");
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
			/*	if (fileDir == null || !fileDir.exists()) {
					fileDir = new File(FileManager.getSaveApkPath());
					System.out
							.println("-------------2--fileDir-----" + fileDir);
					if (fileDir.exists() || fileDir.mkdirs()) {
						file = new File(fileDir.getPath() + "/"
								+ downloadFileName);
						System.out.println("-------------2--file-----"
								+ file.getPath());
						if (file.exists() && file.isFile()) {
							// install() ;
							Message msg = handler.obtainMessage();
							msg.what = DOWNLOAD_ALEARD;
							handler.sendMessage(msg);
						} else {
							try {
								System.out
										.println("-------------2--download-----");
								DownloadUtils.download(downloadUrl, file,
										false, downloadListener);
							} catch (Exception e) {
								Message msg = handler.obtainMessage();
								msg.what = DOWNLOAD_FAIL;
								handler.sendMessage(msg);
								e.printStackTrace();
							}
						}
					}
				}
				stopSelf();*/
				
				if(fileDir == null || !fileDir.exists()){
					fileDir = new File(FileManager.getSaveApkPath());
					if (fileDir.exists() || fileDir.mkdirs()) {
					file = new File(fileDir.getPath() + "/"
							+ downloadFileName);
							try {
							//	System.out
							//			.println("-------------2--download-----");
								DownloadUtils.download(downloadUrl, file,
										false, downloadListener);
							} catch (Exception e) {
								Message msg = handler.obtainMessage();
								msg.what = DOWNLOAD_FAIL;
								handler.sendMessage(msg);
								e.printStackTrace();
							}
					}
				}else{
					file = new File(fileDir.getPath() + "/"
							+ downloadFileName);
					if (file.exists() && file.isFile()) {
						Message msg = handler.obtainMessage();
						msg.what = DOWNLOAD_ALEARD;
						handler.sendMessage(msg);
					}else{
						try {
							//System.out
								//	.println("-------------2--download-----");
							DownloadUtils.download(downloadUrl, file,
									false, downloadListener);
						} catch (Exception e) {
							Message msg = handler.obtainMessage();
							msg.what = DOWNLOAD_FAIL;
							handler.sendMessage(msg);
							e.printStackTrace();
						}
					}
				}
				
				stopSelf();
			}
		}).start();

	}

	/*
	 * class AppUpgradeThread extends Thread {
	 * 
	 * @Override public void run() { // TODO Auto-generated method stub if
	 * (fileDir == null) { fileDir = new File(FileManager.getSaveApkPath());
	 * System.out.println("-------------2--fileDir-----" + fileDir); if
	 * (fileDir.exists() || fileDir.mkdirs()) { file = new
	 * File(fileDir.getPath() + "/" + downloadFileName);
	 * System.out.println("-------------2--file-----" + file.getPath());
	 * if (file.exists() && file.isFile()) { // install() ; } else { try
	 * { System.out.println("-------------2--download-----");
	 * DownloadUtils.download(downloadUrl, file, false, downloadListener);
	 * } catch (Exception e) { Message msg = handler.obtainMessage(); msg.what =
	 * DOWNLOAD_FAIL; handler.sendMessage(msg); e.printStackTrace(); } } } }
	 * stopSelf(); }
	 * 
	 * }
	 */
	 /** 
	* @param apkFile  
	* @retur  void 
	* @Description: 安装apk 
	*/
	public void install(File apkFile){
	        Uri uri = Uri.fromFile(apkFile);
	        Intent intent = new Intent(Intent.ACTION_VIEW);
	        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
	        intent.setDataAndType(uri, "application/vnd.android.package-archive");
	        startActivity(intent);
	    }
	/** 
	* @param apkFile
	* @return  
	* @retur  Intent 
	* @Description: 返回点击安装的Intent
	*/
	public Intent getInstallIntent(File apkFile){
		Uri uri = Uri.fromFile(apkFile);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        return intent ;
	}
}
